/*******************************************************************************
 * Copyright 2010 DemandSpot
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package com.demandspot.utils;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class ServletUtils {

	private static ThreadLocal<HttpServletRequest> servletRequest = new ThreadLocal<HttpServletRequest>();
	private static ThreadLocal<HttpServletResponse> servletResponse = new ThreadLocal<HttpServletResponse>();
	
	public static void setCurrentRequest(HttpServletRequest req) {
		servletRequest.set(req);		
	}

	public static void setCurrentResponse(HttpServletResponse res) {
		servletResponse.set(res);		
	}
	
	public static HttpServletRequest getCurrentRequest() {
		return servletRequest.get();	
	}

	public static HttpServletResponse getCurrentResponse() {
		return servletResponse.get();	
	}
	
	public static HttpSession getCurrentSession() {
		HttpServletRequest req = getCurrentRequest();
		if (req != null) {
			return req.getSession();
		}
		return null;
	}	
	
	public static String getUserIp() {
		HttpServletRequest req = getCurrentRequest();
		if (req != null) {
			return req.getRemoteAddr();
		}
		return null;
	}
	
	public static String getHost() {
		HttpServletRequest req = getCurrentRequest();
		StringBuilder res = new StringBuilder();
		res.append(req.getScheme()).append("://").append(req.getServerName());
		if (req.getServerPort() != 80 && req.getServerPort() != 443) {
			res.append(":").append(req.getServerPort());
		}
		return res.toString();
	}
	
	@SuppressWarnings("unchecked")
	public static String getRequestString() {		
		HttpServletRequest req = getCurrentRequest();
		Map<String, String[]> params = req.getParameterMap();
		StringBuilder res = new StringBuilder(req.getRequestURL());
		
		StringBuilder paramStr = new StringBuilder(); 
		for (Entry<String, String[]> entry : params.entrySet()) {
			for (String value : entry.getValue()) {
				if (paramStr.length() > 0) {
					paramStr.append("&");
				}
				else {
					paramStr.append("?");
				}
				paramStr.append(entry.getKey()).append("=").append(value);
			}
		}		
		res.append(paramStr);		
		return res.toString();
	}

	public static String getReferingHost() {
		return getReferingHost(getCurrentRequest());
	}
	
	public static String getReferingHost(HttpServletRequest req) {
		String referer = req.getHeader("Referer");
				
		if (referer != null && referer.startsWith(req.getScheme() + "://")) {
			referer = referer.substring(7);
			int split = -1;
			int port = referer.indexOf(':');
			int path = referer.indexOf('/');
			if (port > -1) {
				split = port;
			}
			else if (path > -1) {
				split = path;
			}
			
			if (split > -1) {
				referer = referer.substring(0, split);
			}
		}
		
		return referer;
	}

	public static String getUserAgent() {
		return getUserAgent(getCurrentRequest());
	}

	public static String getUserAgent(HttpServletRequest req) {
		return req.getHeader("User-Agent");
	}
	
    public static void createTempDir() {
        String tempDirName = System.getProperty("java.io.tmpdir");
        if (tempDirName == null) {
            throw new RuntimeException("Temporary directory system property (java.io.tmpdir) is null.");
        }

        // create the temporary directory if it doesn't exist
        File tempDir = new File(tempDirName);
        if (!tempDir.exists()) {
            tempDir.mkdirs();
        }
    }
    
    public static void sendStream(ByteArrayOutputStream stream, HttpServletResponse response, String mimeType) throws IOException {
		// Set HTTP headers
		if (mimeType != null) {
			response.setHeader("Content-Type", mimeType);
		}
		response.setHeader("Content-Length", stream.size()+"");

		BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
		stream.writeTo(bos);
		bos.flush();
		stream.close();
		bos.close();				
	}
    
    public static void setSessionAttribute(String name, Object value) {
    	if (getCurrentSession() != null) {
    		getCurrentSession().setAttribute(name, value);
    	}
    }
    
    @SuppressWarnings("unchecked")
	public static <T> T getSessionAttribute(String name) {
    	if (getCurrentSession() != null) {
    		return (T) getCurrentSession().getAttribute(name);
    	}
    	return null;
    }
    
    public static void removeSessionAttribute(String name) {
    	if (getCurrentSession() != null) {
    		getCurrentSession().removeAttribute(name);
    	}
    }
    
    public static String getRequestParam(String name) {
    	if (getCurrentRequest() != null) {
    		return getCurrentRequest().getParameter(name);
    	}
    	
    	return null;
    }
}
